<template>
  <div class="home">
    <el-form ref="form" :model="formData" :rules="rules" label-width="80px">
      <el-form-item label="问题类型" prop="questionType">
        <el-select v-model="formData.questionType" placeholder="请选择">
          <el-option
            v-for="type in questionTypeEnum"
            :key="type.label"
            :label="type.label"
            :value="type.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="问题题目" prop="questionTitle">
        <LanguageDesc ref="titleRef" v-model="formData.questionTitle" isTitle />
      </el-form-item>

      <el-form-item label="问题选项" prop="questionOptions">
        <el-button type="success" :class="{ 'is-disabled': optionCardShow }" @click="addOption">
          添加选项
        </el-button>

        <template v-for="(opt, idx) in formData.questionOptions">
          <LanguageDesc
            ref="langRef"
            :key="idx"
            v-model="formData.questionOptions[idx]"
            :isPass="optionPass"
            :showCard="optionCardShow"
            @cardCancel="onCardCancel(idx, opt)"
            @textDel="onTextDel(idx)"
          />
        </template>
      </el-form-item>

      <el-form-item class="text_r">
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="resetForm">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import LanguageDesc from '@/components/LanguageDesc.vue'
import {
  questionTypeEnum,
  languageTypeEnum,
  languageDesc,
  languageRegs,
  languageKeys
} from '@/const/question'

export default {
  name: 'Home',
  components: {
    LanguageDesc
  },
  data() {
    return {
      questionTypeEnum,
      languageTypeEnum,
      optionPass: false,
      rules: {
        questionType: [{ required: true, message: '请选择问题类型', trigger: 'change' }],
        questionTitle: {
          required: true,
          validator: (rule, value, callback) => {
            // 校验当前语言
            try {
              this.validOptionCard(value, value.activeKey)
            } catch (error) {
              return callback(error)
            }

            // 校验其他语言
            try {
              Object.keys(value).forEach((key) => {
                if (languageKeys.includes(key) && key !== value.activeKey) {
                  this.validOptionCard(value, key)
                }
              })
            } catch (error) {
              return callback(error)
            }

            return callback()
          }
        },
        questionOptions: {
          required: true,
          validator: (rule, value, callback) => {
            this.optionPass = false
            if (!value.length) {
              return callback(new Error('问题选项不能为空'))
            }

            if (this.optionCardShow) {
              const currKey = this.optionCardShow.activeKey
              try {
                this.validOptionCard(this.optionCardShow, currKey)
              } catch (error) {
                return callback(error)
              }

              try {
                Object.keys(this.optionCardShow).forEach((key) => {
                  if (languageKeys.includes(key) && key !== currKey) {
                    this.validOptionCard(this.optionCardShow, key)
                  }
                })
              } catch (error) {
                return callback(error)
              }
            }

            this.optionPass = true
            return callback()
          }
        }
      },
      formData: {
        questionType: null,
        questionTitle: {
          ...languageDesc
        },
        questionOptions: []
      }
    }
  },
  computed: {
    // 当前是否有选项卡片(即正在输入项)
    optionCardShow() {
      return this.formData.questionOptions.find((opt) => !opt.sure)
    }
  },
  methods: {
    // 校验选项卡片
    validOptionCard(option, key) {
      const label = languageTypeEnum.find((ite) => ite.value === key).label
      if (!option[key]) {
        throw new Error(`${label}不能为空`)
      }
      if (!languageRegs[key].test(option[key])) {
        throw new Error(`请输入${label}`)
      }
    },
    checkHasOptionCard() {
      if (this.optionCardShow) {
        this.$message({
          message: '请先确定当前选项',
          type: 'error',
          center: true
        })
      }

      return !!this.optionCardShow
    },
    /* -- start 问题选项 -- */
    addOption() {
      if (this.checkHasOptionCard()) return

      this.formData.questionOptions.push({
        ...languageDesc,
        sure: false
      })
      // 避免校验信息错位
      this.$refs.form.validateField('questionOptions')
    },
    onCardCancel(index, option) {
      if (!option.edit) {
        this.formData.questionOptions.splice(index, 1)
      }
      // 避免校验信息错位
      this.$refs.form.clearValidate('questionOptions')
    },
    onTextDel(index) {
      this.formData.questionOptions.splice(index, 1)
      // Todo: 强制视图更新，否则删除出错
      this.$nextTick(() => {
        this.$refs.langRef.forEach((ref) => {
          ref.init()
        })
      })
    },
    /* -- end -- */
    // 表单提交
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.checkHasOptionCard()) return

          console.log('submit-->', this.formData)
        }
      })
    },
    // 表单重置
    resetForm() {
      this.$refs.form.resetFields()
      // Todo: 强制重置
      this.$refs.titleRef.init(languageDesc)
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 56%;
  margin: 20px auto;
  /deep/.el-button.is-disabled {
    cursor: pointer;
  }
}
</style>
